const { app, BrowserWindow, ipcMain, dialog, session  } = require('electron')
const path = require('path')
const fs = require('fs').promises;
const { processFiles } = require('./fileProcessor.cjs');
const {
  connectMysql,
  isConnected,
  getCurrentConnected,
  showTableList,
  showTableDetail,
  closeConnect,
  showDatabaseList
} = require('./mysql.cjs');

const { decrypt } = require('./tool.cjs');
const {
  DEFAULT_CONFIG, ASE_KEY
} = require('./config.cjs')

let mainWindow = null;

function createWindow() {
  if (mainWindow) {
    return mainWindow;
  }

  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: false,
      webSecurity: false, //是否禁用同源策略(上线时删除此配置)
      preload: path.join(__dirname, 'preload.cjs')
    }
  })

  if (process.env.NODE_ENV === 'development') {
    mainWindow.webContents.openDevTools()
  }

  const startUrl = process.env.VITE_DEV_SERVER_URL || 'http://localhost:3004';
  mainWindow.loadURL(startUrl).catch(() => {
    console.log('Failed to load URL:', startUrl);
    const indexPath = path.join(__dirname, '../dist/index.html');
    if (fs.existsSync(indexPath)) {
      mainWindow.loadFile(indexPath);
    }
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  return mainWindow;
}

app.whenReady().then(() => {
  createWindow();

  ipcMain.handle('select-folder', async () => {
    try {
      const result = await dialog.showOpenDialog(mainWindow, {
        properties: ['openDirectory']
      })
      console.log('Dialog result:', result)
      return result
    } catch (error) {
      console.error('Failed to show open dialog:', error)
      throw error
    }
  })

  ipcMain.handle('check-directory', async (event, dirPath) => {
    try {
      const files = await fs.readdir(dirPath);
      return files.length > 0;
    } catch (error) {
      if (error.code === 'ENOENT') {
        return false;
      }
      throw error;
    }
  });

  ipcMain.handle('show-confirm-dialog', async () => {
    const result = await dialog.showMessageBox(mainWindow, {
      type: 'warning',
      title: '确认覆盖',
      message: '输出目录不为空，继续操作将覆盖现有文件。',
      detail: '是否继续？',
      buttons: ['继续', '取消'],
      defaultId: 1,
      cancelId: 1,
    });
    return result.response === 0;
  });

  ipcMain.handle('process-files', processFiles);

  ipcMain.handle('connect-mysql', connectMysql);

  ipcMain.handle('is-connected', isConnected);

  ipcMain.handle('get-current-connected', getCurrentConnected);

  ipcMain.handle('show-table-list', showTableList);

  ipcMain.handle('show-database-list', showDatabaseList);
  
  ipcMain.handle('show-table-detail', showTableDetail);

  ipcMain.handle('close-connect', closeConnect);
  
  ipcMain.handle('decrypt', decrypt);

  ipcMain.handle('config', async () => DEFAULT_CONFIG);

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
